<template>
  <div style="padding-top: 110px">
    <div class="app-title-container title-position">
      <modules-title titleName="角色管理">
        <template slot="btn">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                v-hasPermi="{v:['sys:role:add']}"
                @click="handleAdd"
                >新增</el-button
              >
            </el-col>
          </el-row>
        </template>
      </modules-title>
    </div>
    <div style="padding: 20px">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item
          label="权限字符"
          prop="roleCode"
          style="margin-left: 40px"
        >
          <el-input
            v-model="queryParams.roleCode"
            placeholder="请输入权限字符"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!--        <el-form-item label="状态" prop="status">-->
        <!--          <el-select-->
        <!--            v-model="queryParams.status"-->
        <!--            placeholder="角色状态"-->
        <!--            clearable-->
        <!--            size="small"-->
        <!--            style="width: 240px"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in statusOptions"-->
        <!--              :key="item.key"-->
        <!--              :label="item.value"-->
        <!--              :value="item.key"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="创建时间">-->
        <!--          <el-date-picker-->
        <!--            v-model="dateRange"-->
        <!--            size="small"-->
        <!--            style="width: 240px"-->
        <!--            value-format="yyyy-MM-dd"-->
        <!--            type="daterange"-->
        <!--            range-separator="-"-->
        <!--            start-placeholder="开始日期"-->
        <!--            end-placeholder="结束日期"-->
        <!--          ></el-date-picker>-->
        <!--        </el-form-item>-->
        <el-form-item style="margin-left: 40px">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            plain
            size="small"
            @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" border :data="roleList" size="medium">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="角色编号" prop="id" align="center" width="120">
          <template slot-scope="scope">
            <span>{{
              (params.pageNum - 1) * params.pageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="角色名称"
          prop="role_name"
          align="center"
          :show-overflow-tooltip="true"
          width="150"
        />
        <el-table-column
          label="权限字符"
          prop="role_code"
          align="center"
          :show-overflow-tooltip="true"
          width="150"
        />
        <el-table-column
          label="显示顺序"
          prop="sort"
          align="center"
          width="100"
        />
        <!--        <el-table-column label="状态" align="center" width="100">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-switch-->
        <!--              v-model="scope.row.status"-->
        <!--              active-value="1"-->
        <!--              inactive-value="0"-->
        <!--              @change="handleStatusChange(scope.row)"-->
        <!--            ></el-switch>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          label="创建时间"
          align="center"
          prop="created_at"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remark"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="medium"
              type="text"
              icon="el-icon-edit"
              v-hasPermi="{v:['sys:role:edit']}"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <!-- <el-button
              size="medium"
              type="text"
              icon="el-icon-circle-check"
              @click="handleDataScope(scope.row)"
            >数据权限</el-button> -->
            <el-button
              size="medium"
              class="text-btn-red"
              type="text"
              icon="el-icon-delete"
              v-hasPermi="{v:['sys:role:delete']}"
              @click="handleDelete(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        style="display: flex; justify-content: flex-end"
        :total="total"
        :page.sync="params.pageNum"
        :limit.sync="params.pageSize"
        @pagination="pagination"
      />
    </div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :destroy-on-close="true"
      :before-close="handleClose"
    >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色顺序" prop="roleSort">
            <el-input-number
              v-model="form.roleSort"
              controls-position="right"
              :min="1"
            />
          </el-form-item>
          <el-form-item label="权限字符" prop="roleCode">
            <el-input v-model="form.roleCode" placeholder="请输入权限字符" />
          </el-form-item>
          <!--        <el-form-item label="状态">-->
          <!--          <el-radio-group v-model="form.status">-->
          <!--            <el-radio label="1">正常</el-radio>-->
          <!--            <el-radio label="0">停用</el-radio>-->
          <!--          </el-radio-group>-->
          <!--        </el-form-item>-->
            <el-form-item label="菜单权限" prop="tree">
              <el-checkbox
                v-model="deptExpand"
                @change="handleCheckedTreeExpand($event, 'tree')"
                >展开/折叠</el-checkbox
              >
              <el-checkbox
                v-model="deptNodeAll"
                @change="handleCheckedTreeNodeAll($event, 'tree')"
                >全选/全不选</el-checkbox
              >
              <div style="height:270px;overflow-y:auto">
                  <el-tree
                  :data="menuOptions"
                  show-checkbox
                  ref="tree"
                  node-key="menu_code"
                  :props="defaultProps"
                  :default-checked-keys="defaultSelect"
                  @check="roleMenuCheck"
                  @check-change="roleMenuChange"
                ></el-tree>
              </div>
            </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色数据权限对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="openDataScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限">
          <el-tree
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button  plain @click="cancelDataScope">取 消</el-button>
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import {
  menuRoot,
  createRole,
  roleList,
  getRoleRoot,
  updateRole,
  deleteRole,
} from "@/api/authorization";
export default {
  data() {
    let tree = (rule, value, callback) => {
      if (this.getMenuAllCheckedKeys().length > 0) {
        callback();
      } else {
        callback(new Error("请至少选择一个角色权限"));
      }
    };
    return {
      title: "",
      open: false,
      openDataScope: false,
      loading: false,
      multiple: true,
      single: true,
      statusOptions: [],
      defaultSelect: [],
      deptExpand: "",
      deptNodeAll: "",
      dateRange: "",
      params: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      queryParams: {
        roleName: "",
        roleCode: "",
      },
      roleList: [],
      form: {
        roleName: "",
        roleSort: "",
        roleCode: "",
        status: "1",
        remark: "",
        dataScope: "",
      },
      defaultProps: {
        children: "children",
        label: "menu_name",
      },
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleCode: [
          { required: true, message: "权限字符不能为空", trigger: "blur" },
        ],
        roleSort: [
           {
            required: true,
            validator: (rule, value, callback) => {
              if (/^(?:[1-9]\d*|0)$/.test(value) == false) {
                callback(new Error("请输入角色顺序,且为正整数"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
          // { required: true, message: "角色顺序不能为空", trigger: "blur" },
        ],
        tree: [{ required: true, validator: tree }],
      },
      menuOptions: [],
      deptOptions: [],
      roleCheckStrictly: true,
      selectCode: [],
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限",
        },
        {
          value: "2",
          label: "自定数据权限",
        },
        {
          value: "3",
          label: "本部门数据权限",
        },
        {
          value: "4",
          label: "本部门及以下数据权限",
        },
        {
          value: "5",
          label: "仅本人数据权限",
        },
      ],
      id: "",
    };
  },
  //是计算属性，也可以理解为一个方法。
  computed: {},
  //属性是手动定义的所需监听的值
  watch: {},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getRoleList();
    this.getRootList();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，未调用不会执行，只执行逻辑，返回值可有可无
  methods: {
    searchName() {
      if (this.queryParams.roleName == "") {
        this.getRoleList();
      }
    },
    searchCode() {
      if (this.queryParams.roleCode == "") {
        this.getRoleList();
      }
    },
    handleCheckedTreeExpand(value, type) {
      if (type == "tree") {
        for (let i = 0; i < this.menuOptions.length; i++) {
          this.$refs.tree.store.nodesMap[
            this.menuOptions[i].menu_code
          ].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "tree") {
        this.$refs.tree.setCheckedNodes(value ? this.menuOptions : []);
      }
    },
    //获取权限列表
    getRootList() {
      let data = {
        menu_name: "",
        menu_status: 1,
      };
      menuRoot(data).then((res) => {
        console.log(res.data);
        this.menuOptions = res.data;
      });
    },
    //获取角色列表
    getRoleList() {
      let data = {
        condition: {
          role_name: this.queryParams.roleName,
          role_code: this.queryParams.roleCode,
        },

        pager: {
          skip: this.params.pageNum,
          limit: this.params.pageSize,
        },
      };
      roleList(data).then((res) => {
        if (res.code == 200) {
          this.total = res.data.total;
          this.roleList = res.data.data;
        }
      });
    },
    pagination(val) {
      this.params.pageSize = val.limit;
      this.params.pageNum = val.page;
      this.getRoleList();
    },
    handleQuery() {
      this.params={
        pageNum: 1,
        pageSize: 10,
      },
      this.getRoleList();
    },
    resetQuery() {
      this.queryParams.roleName = "";
      this.queryParams.roleCode = "";
      this.getRoleList();
    },
    handleAdd() {
      this.reset();
      this.title = "添加角色";
      this.open = true;
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
        this.$refs.form.resetFields();
        this.$refs.form.clearValidate();
      });
    },
    //重置表单
    reset() {
      this.form = {
        roleName: undefined,
        roleSort: undefined,
        roleCode: undefined,
        status: undefined,
        remark: undefined,
        dataScope: undefined,
      };
      this.resetForm("form");
    },
    handleUpdate(row) {
      this.title = "修改角色";
      this.id = row._id;
      this.form.roleName = row.role_name;
      this.form.roleCode = row.role_code;
      this.form.roleSort = row.sort;
      this.form.remark = row.remark;
      this.defaultSelect = [];
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
      });
      // this.open = true
      getRoleRoot(row._id).then((res) => {
        if (res.code == 200) {
          this.defaultSelect = res.data.menu_codes;
        }
      });
      this.open = true;
    },
    handleDelete(id) {
      this.$confirm("确定删除此角色?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteRole(id).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              if (this.roleList.length == 1) {
                this.params.pageNum -= 1;
              }
              this.getRoleList();
            }else{
                this.$message.error(res.msg)
            }
          });
        })
        .catch(() => {});
    },
    //关闭弹窗，重置表单
    handleClose() {
      this.deptExpand = "";
      this.deptNodeAll = "";
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
      });
      this.reset();
      this.defaultSelect = [];
      this.open = false;
    },
    handleSelectionChange() {},
    handleStatusChange() {},
    handleDataScope() {
      this.openDataScope = true;
    },
    roleMenuCheck() {},
    roleMenuChange() {},
    cancel() {
      this.open = false;
      this.reset();
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
      });
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKey = this.$refs.tree.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKey = this.$refs.tree.getHalfCheckedKeys();
      checkedKey.unshift.apply(checkedKey, halfCheckedKey);
      return checkedKey;
    },
    submitForm() {
      this.selectCode = this.getMenuAllCheckedKeys();
      this.$refs.form.validate((valid) => {
        if (valid) {
          let data = {
            role_name: this.form.roleName,
            role_code: this.form.roleCode,
            sort: Number(this.form.roleSort),
            menu_codes: this.selectCode,
            remark: this.form.remark,
          };
          if (this.title == "添加角色") {
            createRole(data).then((res) => {
              console.log(res.data);
              if (res.code == 200) {
                this.$message.success('添加成功')
                this.open = false;
                this.reset();
                this.$refs.tree.setCheckedKeys([]);
                this.$refs.form.resetFields();
              }else{
                this.$message.error(res.msg)
              }
            });
          } else {
            updateRole(this.id, data).then((res) => {
              if (res.code == 200) {
                this.open = false;
                this.reset();
                this.$refs.tree.setCheckedKeys([]);
                this.$refs.form.resetFields();
                this.$message.success('修改成功')
                this.$store.dispatch('user/getInfo')
                this.getRoleList();
              }else{
                this.$message.error(res.msg)
              }
            });
          }
        }
      });
      // this.open = false
    },
    submitDataScope() {
      this.openDataScope = false;
    },
    cancelDataScope() {
      this.openDataScope = false;
    },
  },
};
</script>
<style scoped>
::v-deep .el-button--text {
  padding: 0;
}
</style>
